package cn.lj.controller;

import cn.lj.pojo.Comment;
import cn.lj.pojo.User;
import cn.lj.service.BlogService;
import cn.lj.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @author lj
 * @Description:
 * @date 2020-11-29 14:00
 * @QQ 851477108
 */

@Controller
public class CommentController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private CommentService commentService;

    @Value("${comment.avatar}")
    private String avatar;

    /**
     * 展示留言
     * @param blogId
     * @param model
     * @return
     */
    @GetMapping("/comment/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments", commentService.getCommentByBlogId(blogId));
        return "blog :: commentList";
    }

    /**
     * 提交留言
     * @param comment
     * @param session
     * @return
     */
    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session){
        Long blogId = comment.getBlog().getId();
        //绑定博客与评论
        comment.setBlog(blogService.getDetailedBlog(blogId));
        comment.setBlogId(blogId);

        User user = (User) session.getAttribute("user");
        //用户为管理员时
        if (user != null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            comment.setAvatar(avatar);
        }
        Long ParentCommentId = comment.getParentCommentId();
        if (ParentCommentId == null){
            ParentCommentId = Long.valueOf(-1);
        }
        comment.setParentCommentId(ParentCommentId);
        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }
}
